//
//  ExhibitorElectronicJournalViewController.m
//  ppkc2016
//
//  Created by 拼凑的断音 on 16/3/30.
//  Copyright © 2016年 拼凑的断音. All rights reserved.
//

#import "ExhibitorElectronicJournalViewController.h"
#import "XXTool.h"

#import "ShowExhibitorNameCell.h"
#import "ExhibitorsDetailsViewController.h"
#import "XVVSelectedExhibitionHall.h"
#import "XVVFoldConditionSearch.h"
#import "XVCIndexSelect.h"

#import "XMLHallNumberListModel.h"

@interface ExhibitorElectronicJournalViewController ()<UITableViewDelegate,UITableViewDataSource,DKSortArrayDataSource,XVVFoldConditionSearchDelegate,XVVSelectedExhibitionHallDelegate,UISearchBarDelegate>

@property (nonatomic,strong) UITableView *tableview;

@property (nonatomic,strong) UIView *navigationTopView;

@property (nonatomic,strong) XVVSelectedExhibitionHall *showSelectedView;

@property (nonatomic,strong) XVVFoldConditionSearch *showSearchView;

@property (nonatomic,strong) DKButton* show;

@end

@implementation ExhibitorElectronicJournalViewController
{
    NSMutableArray<RXMLExhibitorInformationModel*> *useData;
    NSMutableArray<RXMLExhibitorInformationModel*> *allExhibitorSaveData; /** < 保存所有参展商数据 */
    NSMutableArray<RXMLExhibitorInformationModel*> *hallSaveData; /** < 选择展馆后参展商数据 */
    DKSortArray *sortUse;
    NSMutableArray *sortRule;
    NSArray <XMLSearchConditionShowModel *> *searchConditionArray;
    UILabel *showSelectionLabel;
}

-(UIView*)navigationTopView
{
    if (_navigationTopView==nil)
    {
        _navigationTopView = [[UIView alloc] initWithFrame:CGRectMake(([UIScreen mainScreen].bounds.size.width-140)/2
                                                                              , (44-30)/2
                                                                              , 140
                                                                              , 30)];
        
        UIImageView *showBackground = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"顶部背景"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
        showBackground.backgroundColor = [UIColor clearColor];
        showBackground.frame = CGRectMake(0
                                          , 0
                                          , 140
                                          , 30);
        [_navigationTopView addSubview:showBackground];
        
        _show = [[DKButton alloc] initWithFrame:CGRectMake(0
                                                           , 0
                                                           , 140
                                                           , 30)];
        [_show setColor:[UIColor clearColor] ForState:DKButtonStateNormal];
        [_show setTintColor:[XXTool colorWithProject]];
        [_show setImage:[UIImage imageNamed:@"向下箭头绿色"]];
        [_show setImageSize:CGSizeMake(20, 9)];
        [_show setImageTitleGap:9];
        [_show setText:NSLocalizedString(@"所有参展商", nil)];
        [_show setTextColor:[XXTool colorWithProject]];
        [_show setImagePosition:DKButtonImagePositionAtEnd];
        if ([XXTool didCurrentLanguageChinese])
        {
            [_show setFont:[XXTool systemFontOfSize:19]];
        }
        else
        {
            [_show setFont:[XXTool systemFontOfSize:16]];
        }
        [_show addTarget:self Select:@selector(showSelectedMenu) ForEvent:DKButtonEventPressedEnd];
        
        [_navigationTopView addSubview:_show];
    }
    return _navigationTopView;
}

-(UITableView*)tableview
{
    if (_tableview==nil)
    {
        _tableview = [[UITableView alloc] init];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorColor = [XXTool colorWithLine];
        _tableview.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        _tableview.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        _tableview.sectionIndexColor = [XXTool colorWithProject];
        _tableview.sectionIndexBackgroundColor = [UIColor clearColor];
        [self.view addSubview:_tableview];
    }
    return _tableview;
}

-(XVVSelectedExhibitionHall*)showSelectedView
{
    if (_showSelectedView==nil)
    {
        _showSelectedView = [[XVVSelectedExhibitionHall alloc] init];
        _showSelectedView.delegate = self;
        [XMLHallNumberListModel requestHallNoListWithComletion:^(BOOL isSuccess, NSMutableArray<XMLHallNumberListModel *> *halllist) {
            if (isSuccess)
            {
                [_showSelectedView setHallButtonArray:halllist];
            }
        }];
        [self.view addSubview:_showSelectedView];
    }
    return _showSelectedView;
}

-(XVVFoldConditionSearch*)showSearchView
{
    if (_showSearchView==nil)
    {
        _showSearchView = [[XVVFoldConditionSearch alloc] init];
        _showSearchView.delegate = self;
        [_showSearchView setConditionSearchData:searchConditionArray];
        [self.view addSubview:_showSearchView];
    }
    return _showSearchView;
}

-(void)initUI
{
    [self.view setBackgroundColor: [XXTool colorWithBackGround]];
    [self.navigationItem setLeftBarButtonItem:[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"更多"] style:UIBarButtonItemStylePlain target:self action:@selector(clickleft)]];
     [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"右上角搜索"] style:UIBarButtonItemStylePlain target:self action:@selector(search)]];
    [self showSelectedView];
    [self.navigationItem setTitleView:self.navigationTopView];
    [self tableview];
    
    
    searchConditionArray = [XMLSearchConditionShowModel localSearchConditionData];
    
    
    useData = [[NSMutableArray alloc] init];
    allExhibitorSaveData = [NSMutableArray array];
    hallSaveData = [NSMutableArray array];
    
    RLMResults *resluts = [RXMLExhibitorInformationModel allObjectsInRealm:[RLMRealm realmWithPath:[XXTool dataBasePath]]];
    for (RXMLExhibitorInformationModel *temp in resluts)
    {
        [useData addObject:temp];
        [allExhibitorSaveData addObject:temp];  //选择展馆点击全部展商时使用
        [hallSaveData addObject:temp]; //先存放所有展商，防止用户没有点击过展馆搜索内容为空时没有数据
    }
    
    sortUse = [[DKSortArray alloc] init];
    sortRule = [[NSMutableArray alloc] init];
    
    for (RXMLExhibitorInformationModel *temp in useData)
    {
        if ([XXTool didCurrentLanguageChinese])
        {
            if ([temp.CompanyName_chn isEqualToString:@""])
            {
                [sortRule addObject:temp.CompanyName_eng];
            }
            else
            {
                [sortRule addObject:temp.CompanyName_chn];
            }
        }
        else
        {
            if ([temp.CompanyName_eng isEqualToString:@""])
            {
                [sortRule addObject:temp.CompanyName_chn];
            }
            else
            {
                [sortRule addObject:temp.CompanyName_eng];
            }
        }
    }
    
    
    [self.view startLoadingWithText:NSLocalizedString(@"数据加载中...", nil)];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [sortUse setArray:sortRule];
        sortUse.dataSource = self;
        [sortUse sort];
        dispatch_async(dispatch_get_main_queue(),^{
            [_tableview reloadData];
            [self.view stopLoading];
        });
    });
    
    showSelectionLabel = [[UILabel alloc] initWithFrame:CGRectMake((self.view.frame.size.width-85)/2, (self.view.frame.size.height-85)/2, 85, 85)];
    UIColor *color = [UIColor colorWithPatternImage:[UIImage imageNamed:@"会刊点击索引.png"]];
    showSelectionLabel.backgroundColor = color;
    showSelectionLabel.textAlignment = NSTextAlignmentCenter;
    showSelectionLabel.textColor = [XXTool colorWithProject];
    showSelectionLabel.font = [XXTool systemFontOfSize:28];
    
    
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickCellLiuyan:) name:@"goneSearch" object:nil];
    
}

-(void)clickCellLiuyan:(NSNotification *)notification{
    [_showSearchView dismiss];
}

-(void)refreshLayout:(CGRect)frame
{
    self.tableview.frame = CGRectMake(0, 0, frame.size.width
                                  , frame.size.height);
    self.showSelectedView.frame = CGRectMake(0, 0, frame.size.width
                                         , frame.size.height);
    self.showSearchView.frame = CGRectMake(0, 0, frame.size.width
                                           , frame.size.height);
}

#pragma mark DKSortArrayDatasource
-(NSString*)DKSortArray:(DKSortArray *)object stringOfSortArray:(NSArray *)dataArray AtIndex:(NSUInteger)index
{
    return sortRule[index];
}

#pragma mark tableviewDatasurce
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString* reuseIdentifier = @"ShowExhibitorNameCell";
    ShowExhibitorNameCell* cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (cell==nil)
    {
        cell = [[ShowExhibitorNameCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
    }
    if (indexPath.row==[tableView numberOfRowsInSection:indexPath.section]-1) //每个section的最后一个cell隐藏line
    {
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    else
    {
        tableView.separatorStyle =UITableViewCellSeparatorStyleSingleLine;
    }
    [cell setCellWithData:useData[[sortUse indexOfSection:indexPath.section AtIndex:indexPath.row]]];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [ShowExhibitorNameCell getCellHeightWithData:useData[[sortUse indexOfSection:indexPath.section AtIndex:indexPath.row]]];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [sortUse numberOfSection];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [sortUse numberOfRowAtSection:section];
}

-(NSArray*)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return [sortUse getTitleArray];
}

-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [[sortUse getTitleArray] objectAtIndex:section];
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
    if (sectionTitle == nil) {
        return  nil;
    }
    
    UILabel * label = [[UILabel alloc] init];
    label.frame = CGRectMake(15, 0, self.view.frame.size.width-15, 35/2);
    label.font=[XXTool systemFontOfSize:14];
    label.text = sectionTitle;
    
    UIView * sectionView = [[UIView alloc] initWithFrame:CGRectMake(0
                                                                    , 0
                                                                    , self.view.frame.size.width-15
                                                                    , 35/2)];
    [sectionView setBackgroundColor:[UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1.0]];
    [sectionView addSubview:label];
    return sectionView;
}

-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
     // 点击 右边字母section
    showSelectionLabel.text = title;
    UIWindow *keyWindows = [[UIApplication sharedApplication] keyWindow];
    [keyWindows addSubview:showSelectionLabel];
    
    if (showSelectionLabel.alpha==0)
    {
        showSelectionLabel.alpha =1;
        [keyWindows addSubview:showSelectionLabel];
    }
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [NSThread sleepForTimeInterval:0.6f];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [UIView animateWithDuration:0.6f
                             animations:^{
                                 showSelectionLabel.alpha = 0;
                             } completion:^(BOOL finished) {
                                 [showSelectionLabel removeFromSuperview];
                             }];
        });
    });

    
    return index;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 35/2;
}

#pragma mark tableDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    RXMLExhibitorInformationModel *temp = useData[[sortUse indexOfSection:indexPath.section AtIndex:indexPath.row]];
    [ExhibitorsDetailsViewController pushViewControllerWithSourceVC:self exhibitorInfo:temp];
}

#pragma mark XVVFoldConditionSearchDelegate
-(void)XVVFoldConditionSearchDidClickTableViewCellWithIndexPath:(NSIndexPath *)indexpath
{
    XMLSearchConditionShowModel * temp = searchConditionArray[indexpath.row];
    
    if ([temp.leftString isEqualToString:NSLocalizedString(@"国家", nil)])
    {
        [XVCIndexSelect pushIndexSelectVCWithSourceVC:self isUseCountryShow:YES nowType:XVCIndexSelectUseSearchExhibitor];
    }
    else if ([temp.leftString isEqualToString:NSLocalizedString(@"类别", nil)])
    {
        [XVCIndexSelect pushIndexSelectVCWithSourceVC:self isUseCountryShow:NO nowType:XVCIndexSelectUseSearchExhibitor];
    }
}

-(void)foldConditionSeach:(XVVFoldConditionSearch *)seachView seachBarTextDidChange:(NSString *)changText
{
    if ([changText isEqualToString:@""])
    {
        useData = hallSaveData;
    }
    else
    {
        NSMutableArray <RXMLExhibitorInformationModel*> *tempArray = [NSMutableArray array];
        for (RXMLExhibitorInformationModel *temp in hallSaveData)
        {
            if ([temp.CompanyName_chn localizedCaseInsensitiveContainsString:changText]||[temp.CompanyName_eng localizedCaseInsensitiveContainsString:changText])
            {
                [tempArray addObject:temp];
            }
        }
        
        useData = tempArray;
    }
    sortRule = [[NSMutableArray alloc] init];
    
    for (RXMLExhibitorInformationModel *temp in useData)
    {
        if ([XXTool didCurrentLanguageChinese])
        {
            if ([temp.CompanyName_chn isEqualToString:@""])
            {
                [sortRule addObject:temp.CompanyName_eng];
            }
            else
            {
                [sortRule addObject:temp.CompanyName_chn];
            }
        }
        else
        {
            if ([temp.CompanyName_eng isEqualToString:@""])
            {
                [sortRule addObject:temp.CompanyName_chn];
            }
            else
            {
                [sortRule addObject:temp.CompanyName_eng];
            }
        }
    }
    
    [sortUse setArray:sortRule];
    [sortUse sort];
    [_tableview reloadData];
}

//-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
//{
//    [_showSearchView dismiss];
//}

#pragma mark XVVSelectedExhibitionHallDelegate
-(void)selectedExhibitionhallDidClickHallWithHallText:(NSString *)hallText
{
    _showSearchView.searchView.searchbar.text = @"";  //清空searchbar搜索内容
    [_show setText:hallText];
    [_show setImage:[UIImage imageNamed:@"向下箭头绿色"]];
    if (([hallText containsString:@"N"] ||
         [hallText containsString:@"E"] ||
         [hallText containsString:@"W"]) &&
        ![hallText isEqualToString:NSLocalizedString(@"所有参展商", nil)])
    {
        NSString *hallNo = [hallText substringFromIndex:1];
        RLMResults *searchResults = [RXMLExhibitorInformationModel objectsInRealm:[RLMRealm realmWithPath:[XXTool dataBasePath]] where:[NSString stringWithFormat:@"HallNo CONTAINS '%@'",hallNo]];
        
        useData = [NSMutableArray array];
        for (RXMLExhibitorInformationModel *temp in searchResults)
        {
            [useData addObject:temp];
        }
        
    }
    else
    {
        useData = allExhibitorSaveData;
    }
    
    hallSaveData = useData; //将选择完展馆后的数据保存到该数组
    sortRule = [[NSMutableArray alloc] init];
    
    for (RXMLExhibitorInformationModel *temp in useData)
    {
        if ([XXTool didCurrentLanguageChinese])
        {
            if ([temp.CompanyName_chn isEqualToString:@""])
            {
                [sortRule addObject:temp.CompanyName_eng];
            }
            else
            {
                [sortRule addObject:temp.CompanyName_chn];
            }
        }
        else
        {
            if ([temp.CompanyName_eng isEqualToString:@""])
            {
                [sortRule addObject:temp.CompanyName_chn];
            }
            else
            {
                [sortRule addObject:temp.CompanyName_eng];
            }
        }
    }
    
    [sortUse setArray:sortRule];
    [sortUse sort];
    [_tableview reloadData];
}

#pragma mark click
-(void)search
{
    [_showSearchView showStausChange];
    if (_showSelectedView.isShow)
    {
        [_showSelectedView showStausChange];
    }
    if (_showSelectedView.isShow)
    {
        [_show setImage:[UIImage imageNamed:@"箭头向上绿色"]];
    }
    else
    {
        [_show setImage:[UIImage imageNamed:@"向下箭头绿色"]];
    }
}

-(void)showSelectedMenu
{
    [_showSelectedView showStausChange];
    if (_showSelectedView.isShow)
    {
         [_show setImage:[UIImage imageNamed:@"箭头向上绿色"]];
    }
    else
    {
         [_show setImage:[UIImage imageNamed:@"向下箭头绿色"]];
    }
    if (_showSearchView.isShow)
    {
        [_showSearchView showStausChange];
    }
}

-(void)clickleft
{
    //[self.navigationController.sideViewController showLeftView];
    [self.navigationController popViewControllerAnimated:YES];
}

@end
